package com.tiantian.user.service;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tiantian.common.core.exception.BusinessException;
import com.tiantian.common.core.utils.StringUtils;
import com.tiantian.user.domain.entity.SysInvite;
import com.tiantian.user.domain.entity.SysUser;
import com.tiantian.user.domain.model.RegisterBody;
import com.tiantian.user.mapper.SysUserRoleMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 注册校验方法
 */
@RequiredArgsConstructor
@Service
public class SysRegisterService {

    private final SysUserService userService;
    private final SysInviteService inviteService;
    private final SysUserRoleMapper sysUserRoleMapper;

    /**
     * 注册
     */
    @Transactional(rollbackFor = Exception.class)
    public void register(RegisterBody registerBody) {
        SysInvite sysInvite = inviteService.selectByInviteCode(registerBody.getInvitationCode());
        if (ObjectUtil.isEmpty(sysInvite)) {
            throw new BusinessException("邀请码不存在");
        }
        String username = registerBody.getUsername();
        String password = registerBody.getPassword();
        // 查询是否已经注册
        if (!userService.checkUserNameUnique(registerBody.getUsername())) {
            throw new BusinessException(StringUtils.format("{} 该用户已经存在", username));
        }
        // 属性拷贝
        SysUser sysUser = BeanUtil.copyProperties(registerBody, SysUser.class);
        sysUser.setUserName(registerBody.getUsername());

        // 设置默认头像
        sysUser.setAvatar("http://10.226.8.14:9000/jx-welcome-minio/default_avatar.png");
        // 使用bcrypt加密算法
        sysUser.setPassword(BCrypt.hashpw(password));

        // 设置创建人
        SysUser createUser = userService.selectUserById(sysInvite.getUserId());
        sysUser.setCreateBy(createUser.getNickName());
        sysUser.setCreateTime(LocalDateTime.now());

        // 设置用户类型 "00"协会内用户 "01"新人用户
        String userType = sysInvite.getUserType();
        sysUser.setUserType(userType);
        // 新增用户
        boolean regFlag = userService.registerUser(sysUser, sysInvite.getRoleId());

        // 设置角色
        int count = sysUserRoleMapper.insertUser(sysUser.getUserId(), sysInvite.getRoleId());
        if (!regFlag && count <= 0) {
            throw new BusinessException(StringUtils.format("[ {} ] 账号: {} , 注册失败请联系管理员", registerBody.getNickName(), registerBody.getUsername()));
        }
    }

}
